package com.xyh.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyh.system.mapper.RoleMapper;
import com.xyh.system.mapper.RoleMenuMapper;
import com.xyh.system.mapper.RoleOperatorMapper;
import com.xyh.system.model.Role;
import com.xyh.system.model.RoleMenu;
import com.xyh.system.model.RoleOperator;
import com.xyh.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kyle
 * @since 2021-01-05
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private RoleOperatorMapper roleOperatorMapper;

    @Override
    public Page<Role> selectAllByQuery(Integer page, Integer limit, Role roleQuery) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if (roleQuery != null) {
            queryWrapper.like(
                    roleQuery.getRoleName() != null && !roleQuery.equals(""),
                    "role_name",
                    roleQuery.getRoleName());
        }
        Page<Role> pages = new Page<>((page - 1), limit);
        Page<Role> rolePage = roleMapper.selectPage(pages, queryWrapper);
        return rolePage;
    }

    @Override
    public Integer[] getMenusByRoleId(Integer roleId) {
        return roleMenuMapper.getMenusByRoleId(roleId);
    }

    @Override
    public Integer[] getOperatorsByRoleId(Integer roleId) {
        return roleOperatorMapper.getOperatorsByRoleId(roleId);
    }

    @Override
    @Transactional
    public void grantMenu(Integer roleId, Integer[] menuIds) {
        //删除所有与roleId相关的菜单menuId
        roleMenuMapper.delete(new QueryWrapper<RoleMenu>().eq("role_id", roleId));
        if (menuIds != null && menuIds.length != 0) {
            //重新分配menuid
            roleMenuMapper.insertRoleMenus(roleId, menuIds);
        }
    }

    @Override
    @Transactional
    public void grantOperator(Integer roleId, Integer[] operatorIds) {
        //先删除role_operator表中角色对应的功能权限
        roleOperatorMapper.delete(new QueryWrapper<RoleOperator>().eq("role_id", roleId));

        if (operatorIds != null && operatorIds.length != 0) {
            for (int i = 0; i < operatorIds.length; i++) {
                //由于界面为了不和menuId冲突，+10000
                //这里在操作时，需要减去 -10000
                operatorIds[i] = operatorIds[i] - 10000;
            }
            //再给role_operator表中添加角色对应的功能权限
            roleOperatorMapper.insertRoleOperators(roleId, operatorIds);
        }
    }
}
